package com.example.mvvmdemo.domain.usecase;

import com.example.mvvmdemo.data.network.SchedulerProvider;

import javax.inject.Inject;

import io.reactivex.Observable;
import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.observers.DisposableObserver;

public class UseCase  {

    private final CompositeDisposable compositeDisposable = new CompositeDisposable();

    private final SchedulerProvider schedulerProvider;

    @Inject
    protected UseCase(SchedulerProvider schedulerProvider) {
        this.schedulerProvider = schedulerProvider;
    }

    public DisposableObserver execute(DisposableObserver useCaseSubscriber, Observable observable) {
        DisposableObserver disposableObserver = (DisposableObserver) observable
            .subscribeOn(schedulerProvider.io())
            .observeOn(schedulerProvider.ui())
            .subscribeWith(useCaseSubscriber);
        compositeDisposable.add(disposableObserver);
        return disposableObserver;
    }


    /**
     * Unsubscribes from current {rx.Subscription}.
     */
    public void unsubscribe() {
        if (!compositeDisposable.isDisposed()) {
            compositeDisposable.dispose();
            compositeDisposable.clear();
        }
    }
}
